//
//  CallApplyViewController.m
//  Molian
//
//  Created by wansong on 4/13/15.
//  Copyright (c) 2015 xiaocan. All rights reserved.
//

#import "CallApplyViewController.h"

#import "CallApplyCell.h"
#import "MLDate.h"

#import "MLUserDataViewController.h"
#import "MLTabBar.h"
#import "MLHomeViewController.h"

@interface CallApplyViewController ()

@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong) Utils * uview;
@end

@implementation CallApplyViewController

#pragma mark - life cycle

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"通话申请";
    self.view.backgroundColor = APPCOLORBACKGROUNDCOLOR(1);
    
    // 右上角按钮
    UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc]initWithTitle:@"忽略所有" style:UIBarButtonItemStyleBordered target:self action:@selector(rejectAllApply)];
    [rightBarButton setTintColor:[UIColor whiteColor]];
    self.navigationItem.rightBarButtonItem = rightBarButton;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kNavigationBarHeight, DeviceWidth, DeviceHeight-kNavigationBarHeight)style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.scrollsToTop = YES;
    self.tableView.tableHeaderView = [[UIView alloc] init];
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.separatorColor = RGBA(225, 225, 225, 1);//分隔条颜色
    self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 51, 0);//滚动条偏移量
    [self.view addSubview:self.tableView];
    
    if(self.dateApplyList.count == 0){
        MLUser *currentUser = [MLUser currentUser];
        AVQuery *dateApplyQuery = [MLDate query];
        [dateApplyQuery whereKey:@"user" equalTo:currentUser];
        [dateApplyQuery includeKey:@"sponsor"];
        [dateApplyQuery whereKey:@"status" equalTo:[NSNumber numberWithInt:MLDateStatus_APPLYING]];
        [dateApplyQuery orderByDescending:@"updatedAt"];
        [dateApplyQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            if (!error) {
                self.dateApplyList = [[NSMutableArray alloc]initWithArray:objects];
                if (self.dateApplyList.count>0) {
                    _uview.viewPrompt.hidden= YES;
                    [self.tableView reloadData];
                }else{
                    _uview.viewPrompt.hidden= NO;
                }
            }
        }];
    }
    [self thsq];
}

-(void)thsq
{
    _uview = [[Utils alloc]init];
    [_uview viewControllerPrompt:self.view.bounds Text:@"没有通话申请~" Image:[UIImage imageNamed:@"news_apply-for-phone_blank_img"]];
    [self. view addSubview:_uview.viewPrompt];
    if(self.dateApplyList.count == 0){
        _uview.viewPrompt.hidden = NO;
    }else{
        _uview.viewPrompt.hidden = YES;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    if ([self isViewLoaded]&&!self.view.window) {
        self.view  = nil;
    }
    // Dispose of any resources that can be recreated.
}

#pragma mark tableview delegate

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static  NSString *CellIdentifier = @"CallApplyCell";
    CallApplyCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if  (cell == nil) {
        cell = [[CallApplyCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
    }
    // 申请通的屌丝
    if ([self.dateApplyList count] == 0) {
        return cell;
    }
    MLDate *dateApply = self.dateApplyList[indexPath.row];
    MLUser *sponsor = (MLUser *)dateApply.sponsor;
    
    cell.dateApply = dateApply;
    cell.nameLabel.text = sponsor.nickname;
    if (!sponsor.subAvatar || [sponsor.subAvatar isEqualToString:@""]) {
        [cell.avatarImgView sd_setImageWithURL:[NSURL URLWithString:sponsor.avatar.url] placeholderImage:[UIImage imageNamed:@"common_avatar_loading_background"]];
        
    }else{
        [cell.avatarImgView sd_setImageWithURL:[NSURL URLWithString:sponsor.subAvatar] placeholderImage:[UIImage imageNamed:@"common_avatar_loading_background"]];
    }
   
    cell.ageLabel.text = [NSString stringWithFormat:@"%ld", (long)[sponsor getUserAge]];
    
    if (MLUserGender_MALE == sponsor.gender) {
        [cell.ageLabel setBackgroundColor:RGBA(162, 200, 243, 1)];
    } else {
        [cell.ageLabel setBackgroundColor:RGBA(245, 163, 179, 1)];
    }
    cell.locationLabel.text = sponsor.selectCity;
    
    cell.acceptBtn.tag = indexPath.row;
     
    [cell.acceptBtn addTarget:self action:@selector(acceptDateApply:) forControlEvents:UIControlEventTouchUpInside];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    
    return  cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
//    MLTabBar *tabBar = (MLTabBar *)self.tabBarController;
//    MLHomeViewController *homeView = (MLHomeViewController *)tabBar.homeNavigation.topViewController;
    
    MLDate *dateApply = self.dateApplyList[indexPath.row];
    MLUser *sponsor = (MLUser *)dateApply.sponsor;
    MLUserDataViewController *userInfoVC = [[MLUserDataViewController alloc]init];
    userInfoVC.userData = sponsor;
    [Utils pushTabbarHidden:userInfoVC Selfvc:self];
}

//cell个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.dateApplyList count];;
}

//设置行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    // 每个cell的头部间距
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section;
{
    //每个cell的底部间距
    return 0;
}

#pragma mark - user interaction

// 接受通话申请
- (void)acceptDateApply:(UIButton *)sender {
    [AVAnalytics event:@"我愿意（通话申请）"]; // 通知服务器一个点击事件。
    MLDate *dateApply = self.dateApplyList[sender.tag];
    sender.enabled = NO;
    MLUser *sponsor = (MLUser *)dateApply.sponsor;
    if ([MLUser currentUser].type != MLUserType_NORMAL&&sponsor.type == MLUserType_NORMAL) {
        dateApply.status = MLDateStatus_ACCEPTED;
    }else{
        dateApply.status = MLDateStatus_SUCCEED;
    }
    [dateApply saveInBackground];
    NSDictionary *params = @{@"touserId": sponsor.objectId, @"fromuserId": [MLUser currentUser].objectId,@"nick":[MLUser currentUser].nickname};
    [AVCloud callFunctionInBackground:@"sendChatAgreeMsg" withParameters:params block:^(id object, NSError *error) {
       
        if(!error){
            // 给用户发送通话申请被同意的消息
            NSDictionary *ext = @{@"notification": EMMESSAGE_EXT_TYPE_CALL_APPLY_ACCEPTED};
            
            [EaseSDKHelper sendTextMessage:@"我已经同意了你的通话申请,等你电话哦。" to:sponsor.objectId messageType:eMessageTypeChat requireEncryption:NO messageExt:ext];
            
            
            //直接移除,否则现在点击忽略所有则出现问题
            [self.dateApplyList removeObject:dateApply];
            [self.tableView reloadData];
            [self thsq];
        }
         sender.enabled = YES;
    }];
}

- (void)rejectAllApply {
    // 忽略所有
    if (![self.dateApplyList count]) {
        [HUD Prompt:@"没有可以忽略的~"];
        return;
    }
    
    HUD*hud = [[HUD alloc]init];
    [hud HUDImage:nil Title:@"忽略所有" Content:@"确定要忽略所有通话申请?" CANCEL:@"取消" Confirm:@"确定"];
    hud.Confirm  = ^{
        for (MLDate *dateApply in self.dateApplyList) {
            [dateApply deleteInBackground];
        }
        [self thsq];
        [self.dateApplyList removeAllObjects];
        // 刷新列表
        [self.tableView reloadData];
    };
    hud.Cancel = ^{
        NSLog(@"取消");
    };
    [self.view addSubview:hud];
}

@end
